<?php

namespace app\model\v1\gift;

use app\model\user\User;
use crmeb\traits\ModelTrait;
use think\Exception;
use think\facade\Db;
use think\Model;


class GiftCardReport extends Model
{

    use ModelTrait;

    protected $updateTime = false;
    protected $createTime = false;

    protected $hidden = [
    //    'create_time','update_time','delete_time'
    ];

    protected $table = 'eb_gift_card_report';


    public function carduser()
    {
        return $this->hasOne (GiftCardUser::class,'id','card_user_id');
    }

    public function user()
    {
        return $this->hasOne (User::class,'uid','uid');
    }


    /**
     * 获取挂失记录列表
     * @param $params
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getGiftReportList($params = [])
    {
        $data['data'] = self::field("*")
            ->with([
                'carduser'=> function($query) {
                    $query->field ('id,uid,gift_card_id,number,is_rec,status,reason,address_id,custom_price');
                },
            ])
            ->where("uid", $params['uid'])
            ->where("type", 2)
            ->page($params['page'], $params['limit'])
            ->order('id','desc')
            ->select()->toArray();

        $data['count'] = self::field('*')
            ->with([
                'carduser'=> function($query) {
                    $query->field ('id,uid,gift_card_id,number,is_rec,status');
                },
            ])
            ->where("uid", $params['uid'])
            ->where("type", 2)
            ->count();
        return $data;
    }





    /**
     * 礼品卡后台 - 挂失管理列表
     * @param $param
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getReportGiftList($param = [])
    {
        $data["data"] = self::field ("*,FROM_UNIXTIME(create_time) as create_time, 
                 case when status=0 then '处理中' 
                    when status=1 then '已通过' 
                    when status=3 then '已冻结' 
                    when status=4 then '领取' 
                    end as status_text 
            ")
            ->whereNull("delete_time")
            ->where(function ($query) use ($param){
                if(!empty($param['time'])){
                    $wheretime = explode (',',$param['time']);
                    $query->where('create_time', 'between', [strtotime($wheretime[0]),strtotime($wheretime[1])]);
                }
                if(!empty($param["word"])) $query->where("content",'like', '%'.$param["word"].'%');
            })
            ->order("id", "desc")
            ->page($param['page'], $param['limit'])
            ->select()->toArray();

        $data["count"] = self::field ("*")
            ->whereNull("delete_time")
            ->where(function ($query) use ($param){
                if(!empty($param['time'])){
                    $wheretime = explode (',',$param['time']);
                    $query->where('create_time', 'between', [strtotime($wheretime[0]),strtotime($wheretime[1])]);
                }
                if(!empty($param["word"])) $query->where("content",'like', '%'.$param["word"].'%');
            })
            ->count();

        return $data;
    }


    /**
     * 挂失管理列表 - 添加
     * @param $param
     * @return int|string
     */
    public static function addReportGift($param = [])
    {
        $card_user_info = GiftCardUser::where("order_id", $param["order_id"])->find() ?? [];
        if(empty($card_user_info)) Throw new Exception("没有此订单!");

        $add = [
            "uid"           => $card_user_info["uid"] ?? '',
            "card_user_id"  => $card_user_info["id"] ?? '',
            "order_id"      => $param["order_id"] ?? '',
            "content"       => $param["content"] ?? '',
            "phone"         => $param["phone"] ?? '',
            "user_name"     => $param["user_name"] ?? '',
            "idcard"        => $param["idcard"] ?? '',
            "type"          => 2,
            "create_time"   => time(),
        ];
        return self::insert($add);
    }




    /**
     * 挂失管理列表 - 编辑
     * @param $param
     * @return RecruitLanguage
     */
    public static function updateReportGift($param = [])
    {
        $update["update_time"] = time();  //更新时间
        if(!empty($param["content"]))      $update["content"] = $param["content"];
        if(!empty($param["phone"]))        $update["phone"] = $param["phone"];
        if(!empty($param["user_name"]))    $update["user_name"] = $param["user_name"];
        if(!empty($param["idcard"]))       $update["idcard"] = $param["idcard"];
        if(!empty($param["order_id"]))     $update["order_id"] = $param["order_id"];
        if(!empty($param["status"]))       $update["status"] = $param["status"];

        if($param["status"] > 0){
            GiftCardUser::where("id", $param["card_user_id"])->update(["delete_time" => time()]);
        }

        return self::where("id", $param["id"])->update($update);
    }


    /**
     * 分类管理列表 - 启用禁用
     * @param $param
     * @return string
     */
    public static function enableReportGift($param = [])
    {
        //获取用户发送的id，根据状态修改当前banner的启用禁用状态
        $status = self::where("id", $param['id'])->value("status");
        $msg = '';
        if($status == 1){   //1启用 2禁用
            $enable = 2;
            $msg = "禁用成功";
        }else{
            $enable = 1;
            $msg = "启用成功";
        }
        self::where("id", $param['id'])->update(['status' => $enable]);
        return $msg;
    }




    /**
     * 礼品卡后台 - 领取管理列表
     * @param $param
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getGiftCardReciveList($param = [])
    {
        $data["data"] = self::alias("a")
            ->field ("a.*,FROM_UNIXTIME(a.create_time) as create_time,b.id as bid,b.number,b.card_pwd,b.gift_card_id,b.is_rec,b.status as bstatus,b.custom_price,FROM_UNIXTIME(b.act_time) as act_time,b.price_text,
            c.id as cid,c.tag_id,d.id as did,d.cate_tag_name,
                case when b.is_rec=1 then '未领取' 
                    when b.is_rec=2 then '已领取' 
                    end as rec_text
            ")
            ->with([
                'user' => function($query) {
                    $query->field("uid,nickname,real_name,phone");
                }
            ])
            ->join('gift_card_user b', 'a.card_user_id=b.id','left')
            ->join('gift_card c', 'b.gift_card_id=c.id','left')
            ->join('gift_card_cate d', 'c.tag_id=d.id','left')
            ->whereNull("a.delete_time")
            ->where(function ($query) use ($param){
                $query->whereIn("a.type", [4]);
                if(!empty($param['time'])){
                    $wheretime = explode (',',$param['time']);
                    $query->where('a.create_time', 'between', [strtotime($wheretime[0]),strtotime($wheretime[1])]);
                }
                if(!empty($param["tag_id"])) $query->where("c.tag_id", $param["tag_id"]);
                if(!empty($param["is_rec"])) $query->where("b.is_rec", $param["is_rec"]);
            })
            ->order("a.id", "desc")
            ->page($param['page'], $param['limit'])
            ->select()->toArray();

        $data["count"] = self::alias("a")->field ("*")
            ->join('gift_card_user b', 'a.card_user_id=b.id','left')
            ->join('gift_card c', 'b.gift_card_id=c.id','left')
            ->join('gift_card_cate d', 'c.tag_id=d.id','left')
            ->whereNull("a.delete_time")
            ->where(function ($query) use ($param){
                $query->whereIn("a.type", [4]);
                if(!empty($param['time'])){
                    $wheretime = explode (',',$param['time']);
                    $query->where('a.create_time', 'between', [strtotime($wheretime[0]),strtotime($wheretime[1])]);
                }
                if(!empty($param["tag_id"])) $query->where("c.tag_id", $param["tag_id"]);
                if(!empty($param["is_rec"])) $query->where("b.is_rec", $param["is_rec"]);
            })
            ->count();

        return $data;
    }



    /**
     * 领取管理列表 - 详情
     * @param $param
     * @return GiftCardUser|array|mixed|Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function detailGiftCardRecive($param = [])
    {
        $detail = self::alias("a")
            ->field ("a.*,FROM_UNIXTIME(a.create_time) as create_time,b.id as bid,b.number,b.card_pwd,b.gift_card_id,b.is_rec,b.custom_price,b.act_time,b.price_text,
            c.id as cid,c.tag_id,d.id as did,d.cate_tag_name,
                case when b.is_rec=1 then '未领取' 
                    when b.is_rec=2 then '已领取' 
                    end as rec_text
            ")
            ->with([
                'user' => function($query) {
                    $query->field("uid,nickname,real_name,phone");
                }
            ])
            ->join('gift_card_user b', 'a.card_user_id=b.id','left')
            ->join('gift_card c', 'b.gift_card_id=c.id','left')
            ->join('gift_card_cate d', 'c.tag_id=d.id','left')
            ->where("a.id", $param["id"])
            ->find();

        return $detail;
    }

}